package com.justech.eat.service.impl;

import com.justech.eat.entity.Order;
import com.justech.eat.entity.OrderDetail;
import com.justech.eat.service.CacheCapableOrderDetailService;
import com.justech.eat.service.OrderApplicationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @program: eat-service
 * @description:
 * @author: feifei.li
 * @create: 2020-06-16 09:15
 **/
@Service
public class CacheCapableOrderDetailServiceImpl extends OrderDetailServiceImp implements CacheCapableOrderDetailService {
    @Autowired
    OrderApplicationService orderApplicationService;
    @Autowired
    RedisTemplate redisTemplate;

    /** 已经订版的订单信息key **/
    public static final String ORDERED_DETAIL = "ordered_detail";

    protected String subHashKey(String date, String jobNumber, int type) {
        if (StringUtils.isBlank(date) || StringUtils.isBlank(jobNumber) || type == 0) {
            throw new RuntimeException("String date, String jobNumber, int type Can't be empty");
        }
        return date + "_" + jobNumber + "_" + type;
    }

    /**
     * 查询某个日期数据，注入到缓存中
     *
     * @param date
     */
    @Override
    public void irrigation(String date) {
        Long size = redisTemplate.opsForHash().size(date);
        if (size > 0) {
            return;
        }
        List<Order> orders = orderApplicationService.getByDate(date);
        for (Order order : orders) {
            List<OrderDetail> details = order.getOrderDetails();
            for (OrderDetail detail : details) {
                String key = subHashKey(date, order.getJobNumber(), detail.getType());
                redisTemplate.opsForHash().put(ORDERED_DETAIL, key, detail);
            }
        }
    }

    /**
     * 清除缓存
     *
     * @param date
     */
    @Override
    public void clear(String date) {
        redisTemplate.opsForHash().delete(ORDERED_DETAIL);
    }

    /**
     * 查询用户订餐记录
     *
     * @param date
     * @param jobNumber
     * @param type
     * @return
     */
    @Override
    public OrderDetail getOrderDetail(String date, String jobNumber, int type) {
        return (OrderDetail) redisTemplate.opsForHash().get(ORDERED_DETAIL, subHashKey(date, jobNumber, type));
    }
}
